package com.lib.online.controller;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.lib.online.model.User;
import com.lib.online.model.dto.LoginDTO;
import com.lib.online.service.UserService;
 

@Controller
@SessionAttributes("curUser")
public class UserController {

	@Autowired
    UserService userService;

	@Autowired
    private MessageSource messageSource;
	 
	
	@RequestMapping(value = "reg_init", method = {RequestMethod.POST, RequestMethod.GET})  
	  public String userNodelInit(@RequestParam("login") boolean login, Model model) {
		if (login) {	
			model.addAttribute("loginDTO", new LoginDTO());			
			 return "login";
		} else {		
			model.addAttribute("newUser", new User());
			return "register";
		}
	  }
	  
	
	  @RequestMapping(value = "login", method = {RequestMethod.POST, RequestMethod.GET})  
	    public String loginUser(@ModelAttribute("loginDTO") @Valid LoginDTO loginObj, BindingResult br, Model  model, Locale locale) {
		 
		 if (!br.hasErrors()) {						 
			 User user = this.userService.getUser(loginObj.getName(), loginObj.getPassword());
			 if (user==null) {
				 String errorMessage = messageSource.getMessage("Wrong.user.name", null, locale);
				 model.addAttribute("message", errorMessage);			
				 return "login";
			 }
			  model.addAttribute("curUser", user);			
			  return "redirect:/browse";			  
			} else {
				 return "login";
			}
            		 
	       
	    }
	  
	  @RequestMapping(value="/{username}/edit", method = {RequestMethod.POST, RequestMethod.GET})
		public String editUser(
				@PathVariable String username,
				@ModelAttribute("curUser") @Valid User user, 
				BindingResult br,
				Model model,  HttpServletRequest request) {
		 
			if (request.getMethod().equals("GET")) 
				return "editUser";
			else {
		  
			if (br.hasErrors()) {
				
				return "editUser";
			}
						
			this.userService.addUser(user);
			//model.addAttribute("curUser", user);
			return "redirect:/browse";
			}
		}
	  
	  
	  @RequestMapping(value = "{username}/books", method = RequestMethod.GET) 
	   public String getUserLibrary(@PathVariable String username, Model  model) {
		  User user = (User) model.asMap().get("curUser");
		  
		 if (user!=null && user.getUserFName().equals(username)) {
			model.addAttribute("curUser", userService.getUser(username, user.getPassword()));
			 return "personalLibrary";
		 }
		 else  return "redirect:/browse";					  
	  }
	  
	  @RequestMapping(value = "/add_to_user/{title}", method = RequestMethod.GET) 
	   public String addToUserLibrary(@PathVariable String title, Model  model) {
		  User user = (User) model.asMap().get("curUser");
		  
		 if (user!=null) {
			   try {
			 userService.addUserBook(title, user);
			 model.addAttribute("message", "Book was added successfully!");
			 return "personalLibrary";
			   } catch (Exception ex) {
				   model.asMap().put("message", "Fail while adding book!");
				  				   
			   }
			
				
		 } 
		 
		 return "exception";					  
	  }
	  
	  @RequestMapping(value = "/remove_from_user/{title}", method = RequestMethod.GET) 
	   public String remFromUserLibrary(@PathVariable String title, Model  model) {
		  User user = (User) model.asMap().get("curUser");
		  
		 if (user!=null) {
			 userService.removeUserBook(title, user);
			 
			 model.addAttribute("message", "Book was removed successfully!");
				 return "personalLibrary";
		 } else  return "redirect:/browse";					  
	  }
	  
	  
	  
	  @RequestMapping(value = "logout", method = RequestMethod.GET)  
	   public String logoutUser(ModelMap model, SessionStatus status) {
		  status.setComplete();
	        model.remove("curUser");	     
	        return "redirect:/browse";
	    }
	  
		@RequestMapping(value="register", method = {RequestMethod.POST, RequestMethod.GET})
		public String registerUser(
				@ModelAttribute("newUser") @Valid User user,
				BindingResult br,
				Model model) {
			
			if (br.hasErrors()) {
				
				return "register";
			}
						
			this.userService.addUser(user);
			model.addAttribute("curUser", user);
			return "redirect:/browse";
		}
		
		 @RequestMapping(value = "{username}/delete", method = RequestMethod.GET)  
		   public String deleteUser(@PathVariable String username, Model model, SessionStatus status) {
			 User user = (User) model.asMap().get("curUser");
			  
			 if (user!=null) {
				 userService.removeUser(user);
			  status.setComplete();
		        model.asMap().remove("curUser");	     
		       
		    }
			 
			 return "redirect:/browse";
			 
		 }
		
		
}
